package arrayhelper

import (
	"slices"
	"strconv"
)

// 对数据进行分片
func ArrayChunk[T int | int32 | int64 | string](arr []T, step int64) (segmens [][]T) {
	max := int64(len(arr))
	if max < step {
		segmens = append(segmens, arr)
		return
	}
	var num = max / step
	var beg int64
	var end int64
	for i := int64(0); i < num || end < max; i++ {
		beg = 0 + i*step
		end = beg + step
		if end > max {
			end = max
		}
		segmens = append(segmens, arr[beg:end])
	}
	return
}

// 对数据进行分片
// Deprecated: As of v0.1.43, this function simply calls [arrayhelper.ArrayChunk].
func ArrayChunkInt64(arr []int64, step int64) (segmens [][]int64) {
	segmens = ArrayChunk(arr, step)
	return
}

// int64数组转string数组
func Int64ToStingArray(arr []int64) (idStr []string) {
	if len(arr) <= 0 {
		return
	}
	for _, v := range arr {
		idStr = append(idStr, strconv.FormatInt(v, 10))
	}
	return
}

// string数组转int64数组
func StringToInt64Array(arr []string) (vals []int64) {
	if len(arr) <= 0 {
		return
	}
	for _, v := range arr {
		tmp, err := strconv.ParseInt(v, 10, 64)
		if err == nil {
			vals = append(vals, tmp)
		}
	}
	return
}

// string数组转int数组
func StringToIntArray(arr []string) (vals []int) {
	if len(arr) <= 0 {
		return
	}
	for _, v := range arr {
		tmp, err := strconv.Atoi(v)
		if err == nil {
			vals = append(vals, tmp)
		}
	}
	return
}

// 数组内元素排重
func ArrayUnique[T int | int64 | string](arr []T) (dst []T) {
	if len(arr) <= 0 {
		return
	}
	valMap := make(map[T]bool)
	for _, v := range arr {
		_, ok := valMap[v]
		if ok {
			continue
		}
		valMap[v] = true
		dst = append(dst, v)
	}
	return
}

// 字符串是否在数组中
//
//	func InArray(arr []string, val string) bool {
//		sort.Strings(arr)
//		idx := sort.SearchStrings(arr, val)
//		if idx < len(arr) && arr[idx] == val {
//			return true
//		}
//		return false
//	}
func InArray[T int | int8 | int16 | int32 | int64 | string](arr []T, val T) bool {
	if len(arr) <= 0 {
		return false
	}
	return slices.Contains(arr, val)
}
